package com.koron.order.risk.riskDuty.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.BaseBean;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.util.CodeTools;
import com.koron.order.risk.base.bean.po.LineRiskMeasure;
import com.koron.order.risk.base.bean.po.LineStaff;
import com.koron.order.risk.base.service.LineRiskMeasureService;
import com.koron.order.risk.base.service.LineStaffService;
import com.koron.order.risk.riskDuty.bean.convertor.RiskDutyConvertor;
import com.koron.order.risk.riskDuty.bean.dto.LineRiskDutyDTO;
import com.koron.order.risk.riskDuty.bean.po.LineRiskDuty;
import com.koron.order.risk.riskDuty.bean.query.LineRiskDutyQuery;
import com.koron.order.risk.riskDuty.bean.vo.LineRiskDutyVO;
import com.koron.order.risk.riskDuty.mapper.LineRiskDutyMapper;
import com.koron.order.risk.riskDuty.service.LineRiskDutyService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 风险看护值守单(LineRiskDuty)表服务实现类
 *
 * @author jzp
 * @since 2022-12-22 16:41:53
 */
@Service
public class LineRiskDutyServiceImpl implements LineRiskDutyService {

    final String staffType = "看护值守单-值守人员";
    @Autowired
    private LineStaffService lineStaffService;
    @Autowired
    private RiskDutyConvertor riskDutyConvertor;
    @Autowired
    private LineRiskMeasureService lineRiskMeasureService;

    @Override
    @TaskAnnotation("getById")
    public LineRiskDuty getById(SessionFactory factory, String id) {
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        return mapper.selectById(id);
    }

    /**
     * 通过ID查询单条数据
     *
     */
    @Override
    @TaskAnnotation("getVoById")
    public LineRiskDutyVO getVoById(SessionFactory factory, String id) {
        LineRiskDutyVO lineRiskDuty = riskDutyConvertor.entityToVo(getById(factory, id));
        // 查询值守人员
        List<LineStaff> lineStaffs = lineStaffService.listByOrderId(factory, id);
        lineRiskDuty.setDutyStaffs(lineStaffs);
        return lineRiskDuty;
    }

    @Override
    public LineRiskDutyVO getOneByRiskId(SessionFactory factory, String riskId) {
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        LineRiskDutyQuery query = new LineRiskDutyQuery();
        query.setOrderId(riskId);
        List<LineRiskDutyVO> lineRiskDutyVOS = mapper.selectList(query);
        if (CollUtil.isEmpty(lineRiskDutyVOS)) {
            return null;
        }
        return lineRiskDutyVOS.get(0);
    }

    /**
     * 查询所有数据
     *
     */
    @Override
    @TaskAnnotation("list")
    public List<LineRiskDutyVO> list(SessionFactory factory, LineRiskDutyQuery query) {
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        List<LineRiskDutyVO> lineRiskDutyVOS = mapper.selectList(query);
        if (CollUtil.isEmpty(lineRiskDutyVOS)) {
            return lineRiskDutyVOS;
        }
        List<String> ids = lineRiskDutyVOS.stream().map(BaseBean::getId).collect(Collectors.toList());
        // 查询值守人员
        List<LineStaff> lineStaffs = lineStaffService.listByOrderIds(factory, ids);
        if (CollUtil.isNotEmpty(lineStaffs)) {
            Map<String, List<LineStaff>> collect = lineStaffs.stream().collect(Collectors.groupingBy(LineStaff::getOrderId));
            lineRiskDutyVOS.forEach(e -> e.setDutyStaffs(collect.get(e.getId())));
        }
        return lineRiskDutyVOS;
    }

    @Override
    @TaskAnnotation("page")
    public PageInfo<LineRiskDutyVO> page(SessionFactory factory, PageQuery pageQuery, LineRiskDutyQuery query) {
        return LineRiskDutyService.super.page(factory, pageQuery, query);
    }

    /**
     * 新增数据
     *
     */
    @Override
    @TaskAnnotation("saveDto")
    public boolean saveDto(SessionFactory factory, LineRiskDutyDTO lineRiskDutyDTO) {
        if (lineRiskDutyDTO.getId() == null) {
            String orderId = lineRiskDutyDTO.getOrderId();
            LineRiskDutyQuery query = new LineRiskDutyQuery();
            query.setOrderId(orderId);
            List<LineRiskDutyVO> list = list(factory, query);
            Assert.isTrue(CollUtil.isEmpty(list), "该风险管控单已新增过看护值守");
        } else {
            measureSetImplemented(factory, lineRiskDutyDTO);
        }
        if (lineRiskDutyDTO.getCode() == null) {
            String code = CodeTools.getCodeNo("KHZS", 3);
            lineRiskDutyDTO.setCode(code);
        }
        if (lineRiskDutyDTO.getStatus() == null) {
            lineRiskDutyDTO.setStatus("0");
        }
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        mapper.insertOrUpdate(lineRiskDutyDTO);
        // 2. 保存人员信息
        List<LineStaff> dutyStaffs = lineRiskDutyDTO.getDutyStaffs();
        dutyStaffs.forEach(e -> {
            e.setOrderId(lineRiskDutyDTO.getId());
            e.setStaffType(staffType);
        });
        lineStaffService.removeByOrderId(factory, lineRiskDutyDTO.getId());
        lineStaffService.saveBatch(factory, dutyStaffs);
        return true;
    }

    /**
     * 设置管控措施为已落实
     */
    @Override
    public void measureSetImplemented(SessionFactory factory, LineRiskDuty lineRiskDuty) {
        // 判断是否由未值守变值守中
        LineRiskDuty source = getById(factory, lineRiskDuty.getId());
        // 如果原来是未值守，现在是值守中|已结束，则改为已落实
        if (source != null && "1".equals(source.getStatus()) && StrUtil.equalsAny(lineRiskDuty.getStatus(), "2", "3")) {
            LineRiskMeasure measure = lineRiskMeasureService.getOneByRiskId(factory, lineRiskDuty.getOrderId());
            measure.setImplemented(1);
            lineRiskMeasureService.save(factory, measure);
        }
    }

    /**
     * 值守完成
     */
    @Override
    @TaskAnnotation("end")
    public boolean end(SessionFactory factory, String id) {
        // 1. 修改状态位已完成
        updateStatus(factory, id, "3");
        return true;
    }

    /**
     * 修改数据
     *
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, LineRiskDuty lineRiskDuty) {
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        return mapper.update(lineRiskDuty) > 0;
    }

    @Override
    @TaskAnnotation("updateStatus")
    public boolean updateStatus(SessionFactory factory, String id, String status) {
        LineRiskDuty lineRiskDuty = new LineRiskDuty();
        lineRiskDuty.setId(id);
        lineRiskDuty.setStatus(status);
        return update(factory, lineRiskDuty);
    }

    /**
     * 通过主键删除数据
     *
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        LineRiskDutyMapper mapper = factory.getMapper(LineRiskDutyMapper.class);
        return mapper.hidden(id) > 0;
    }
}
